package com.stbu;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.*;
import java.net.URI;
import java.net.URLEncoder;

@Controller
public class FileController {

    @RequestMapping("/toUpload")
    public String toUploadJsp() {
        return "upload";
    }

    @RequestMapping("/upload")
    public ModelAndView upload(@RequestPart("myfile") MultipartFile multipartFile) {
        ModelAndView modelAndView = new ModelAndView();
        String contentType =  multipartFile.getContentType();
        String destFile = "D:"+ File.separator+ "FileIo" + File.separator;
        File rootFile = new File(destFile);
        System.out.println("文件目标目录:" + rootFile.getAbsolutePath());
        if (!rootFile.exists()) {
            rootFile.mkdir();
        }
        String msg ="";
        File dest = new File(rootFile,multipartFile.getOriginalFilename());
        try {
            multipartFile.transferTo(dest);
            msg = "上传成功";
        } catch (IOException e) {
            e.printStackTrace();
            msg = "上传失败";
        }
        modelAndView.addObject("msg",msg);
        modelAndView.setViewName("info");
        return  modelAndView;
    }

    @RequestMapping("/toDownload")
    public String toDownload() {
        return "download";
    }
    @RequestMapping("/download")
    public ResponseEntity<byte[]>download(@RequestParam("filename") String filename) throws IOException {
        //下载文件的路径(这里绝对路径)
        String filepath= "D:"+ File.separator+ "FileIo" + File.separator+filename;
        File file =new File(filepath);
        //创建字节输入流，这里不实用Buffer类
        InputStream in = new FileInputStream(file);
        //available:获取输入流所读取的文件的最大字节数
        byte[] body = new byte[in.available()];
        //把字节读取到数组中
        in.read(body);
        //设置请求头
        MultiValueMap<String, String> headers = new HttpHeaders();
        headers.add("Content-Disposition", "attchement;filename=" + file.getName());
        //设置响应状态
        HttpStatus statusCode = HttpStatus.OK;
        in.close();
        ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
        return entity;//返回
    }
}
